package com.ljm.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Component
public class SpringBeanUtil implements ApplicationContextAware, DisposableBean {
    private static ApplicationContext applicationContext = null;

    private static final Logger logger = LoggerFactory.getLogger(SpringBeanUtil.class);

    /**
     * 实现ApplicationContextAware接口, 注入Context到静态变量中.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        if (logger.isDebugEnabled()){
            logger.debug("注入ApplicationContext到SpringContextHolder:" + applicationContext);
        }

        if (SpringBeanUtil.applicationContext != null) {
            if (logger.isWarnEnabled()){
                logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:"
                        + SpringBeanUtil.applicationContext);
            }
        }

        SpringBeanUtil.applicationContext = applicationContext; // NOSONAR
    }

    /**
     * 实现DisposableBean接口,在Context关闭时清理静态变量.
     */
    @Override
    public void destroy() throws Exception {
        SpringBeanUtil.clear();
    }

    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        if (applicationContext == null){
            return null;
        }
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> requiredType) {
        if (applicationContext == null){
            return null;
        }
        // assertContextInjected();
        return applicationContext.getBean(requiredType);
    }

    /**
     * 清除SpringContextHolder中的ApplicationContext为Null.
     */
    public static void clear() {
        logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
        applicationContext = null;
    }

    /**
     * 根据类型返回bean列表
     *
     * @param type
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> getBeansForType(Class<T> type) {
        if (applicationContext == null)
            return null;
        String[] beanNameArr = applicationContext.getBeanNamesForType(type);
        List<T> beanNameList = (List<T>) Arrays.asList(beanNameArr);
        List<T> beanList = new ArrayList<T>();
        for (int i = 0; i < beanNameArr.length; i++) {
            if (beanNameArr[i].endsWith("Target")) {
                String serviceBeanName = beanNameArr[i].substring(0, beanNameArr[i].length() - 6) + "Service";
                if (!beanNameList.contains(serviceBeanName))
                    beanList.add((T) applicationContext.getBean(beanNameArr[i]));
            } else {
                beanList.add((T) applicationContext.getBean(beanNameArr[i]));
            }
        }
        return beanList;
    }

    /**
     * 根据类型返回bean列表（去除exceptBeanName）
     *
     * @param type
     * @param exceptBeanName
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> getBeansForType(Class<T> type, String exceptBeanName) {
        if (applicationContext == null)
            return null;
        String[] beanNameArr = applicationContext.getBeanNamesForType(type);
        List<T> beanNameList = (List<T>) Arrays.asList(beanNameArr);
        List<T> beanList = new ArrayList<T>();
        for (int i = 0; i < beanNameArr.length; i++) {
            if (beanNameArr[i].equals(exceptBeanName)){
                continue;
            }
            if (beanNameArr[i].endsWith("Target")) {
                String serviceBeanName = beanNameArr[i].substring(0, beanNameArr[i].length() - 6) + "Service";
                if (!beanNameList.contains(serviceBeanName))
                    beanList.add((T) applicationContext.getBean(beanNameArr[i]));
            } else {
                beanList.add((T) applicationContext.getBean(beanNameArr[i]));
            }
        }
        return beanList;
    }
}
